package com.bsoft.exchange.util;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.bsoft.exchange.dao.idn.IdentityMapper;



/**
 * 主键管理类
 * @author yangxt
 */
@Component
public class IdentityManager {
	
	@Autowired
	private  IdentityMapper identityMapper;
	
	/**
	 * 传入需要获取的表名及需要的主键数量
	 * */

	public  long getMax(String bmc,int count){
		boolean upateOk = true;
		if(count <= 0) return 0;
		bmc = bmc.toUpperCase();
		
		Integer col;
		String sysName ="GY_IDENTITY";
		String temp = "";
		
		col = bmc.indexOf("_");

		temp = bmc.substring(0, 2);
		
		if(col == 0 || "GY".equals(temp) ){
			sysName ="GY_IDENTITY";
		}else{
			sysName ="GY_IDENTITY_" + bmc.substring(0, col).toUpperCase();
		}
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("sysName", sysName);
		map.put("bmc",bmc);
		//获取当前的主键		
		Long max = identityMapper.getMax(map);
		if(max == null)max = 0l;
		
		long maxReturn = 0;
		int ok = 0;
		//主键不存在则新增
		
		map.put("bmc",bmc);
		if(max <= 0){
			
			try {
				map.put("dqz",count);
				identityMapper.insertMax(map);
				ok = 1;
			} catch (Exception e) {
				ok = 0;
			}
			if( ok == 1) {
				maxReturn = 1;
			}else{//可能存在刚刚新增了主键的情况
				max = identityMapper.getMax(map);
				if(max == null)max = 0l;
				if(max > 0){
					try {
						map.put("dqz",max + count);
						identityMapper.updateMax(map);
						ok = 1;
					} catch (Exception e) {
						ok = 0;
					}
					if( ok == 1){
						maxReturn = max + 1;
					} else{
						upateOk = false;
					}
				}
			}
		}else{//更新主键
			try {
				map.put("dqz",max + count);
				identityMapper.updateMax(map);
				ok = 1;
			} catch (Exception e) {
				ok = 0;
			}
			if( ok == 1) {
				maxReturn = max + 1;
			}else{
				upateOk = false;
			}
		}
		if(!upateOk){//连续提交2次
			for(int i = 0;i < 2;i++){
				max = identityMapper.getMax(map);
				if(max == null)max = 0l;
				try {
					map.put("dqz",max + count);
					identityMapper.updateMax(map);
					ok = 1;
				} catch (Exception e) {
					ok = 0;
				}
				if( ok == 1){
					maxReturn = max + 1;
					break;
				}
			}
		}
		return maxReturn;
	}
	
}
